var express = require('express');
var path = require('path');
var log4js = require('./lib/utils/logger');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var moment = require('moment');
var router = require('./lib/utils/router');

var dust = require('dustjs-linkedin'),
    cons = require('consolidate');

dust.helpers = require('dustjs-helpers').helpers;

dust.helpers.moment = function (chunk, context, bodies, params) {
    return chunk.write(moment(params.value).format(params.format || ''));
};

var app = express();

// view engine setup
app.engine('dust', cons.dust);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'dust');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(log4js.connectLogger(log4js.getLogger('access'), {
    level: log4js.levels.INFO,
    format: ':remote-addr :method :url HTTP/:http-version :status ":user-agent" :response-timems',
    nolog: /\/(script|_debug|css)/
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, 'public')));

//app.use(function (req, res, next) {
//    if (!req.session.userId) {
//        if (req.method==='POST' && req.url!=='/user/login') {
//            res.redirect('/user/login');
//        }else{
//            next();
//        }
//    } else {
//        var userService = require('./lib/services/user');
//        userService.queryById(req.session.userId, function (err, user) {
//            res.locals.user = user;
//            next();
//        });
//    }
//});

app.use(router);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
